<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('还款计划') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('还款日期')" prop="repaymentDate">
        <DatePicker v-model="repaymentDate" type="daterange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['financing:repayment:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t('新增') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['financing:repayment:import']"
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >{{ $t('导入') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['financing:repayment:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t('导出') }}</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="dealFinancingRepaymentList" border tooltip-effect="darkTable">
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('还款日期')" align="center" prop="repaymentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.repaymentDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('应还本金（元）')" align="center" prop="principalPayable" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.principalPayable) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('应还利息（元）')" align="center" prop="interestPayable" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.interestPayable) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('应付手续费（元）')" align="center" prop="serviceChargesPayable" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.serviceChargesPayable) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('本次应付总额（元）')" align="center" prop="totalAmountPayable" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.totalAmountPayable) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('当前余额（元）')" align="center" prop="currentBalance" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.currentBalance) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('实际还款日期')" align="center" prop="actualRepaymentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.actualRepaymentDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('实际支付本金（元）')" align="center" prop="actualPrincipalPaid" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.actualPrincipalPaid) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('实际支付利息（元）')" align="center" prop="actualInterestPaid" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.actualInterestPaid) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('实际支付手续费（元）')" align="center" prop="actualServiceChargePaid" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.actualServiceChargePaid) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('本次实际支付总额（元）')" align="center" prop="totalAmountActuallyPaid" width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.totalAmountActuallyPaid) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['financing:repayment:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row,'repayment')"
          >{{ $t('还款') }}</el-button>
          <el-button
            v-hasPermi="['financing:repayment:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row,undefined)"
          >{{ $t('修改') }}</el-button>
          <el-button
            v-hasPermi="['financing:repayment:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改还款计划对话框 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <dealFinancingRepaymentForm ref="dealFinancingRepaymentForm" />
    </el-dialog>

    <!-- 导入 -->
    <el-dialog
      :title="$t('还款计划导入')"
      :visible.sync="upload.open"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport+ '&dealId=' + upload.dealId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('上传') }}</em>
        </div>
        <!--        <div slot="tip" class="el-upload__tip">-->
        <!--          <el-checkbox v-model="upload.updateSupport" /> {{ $t('是否更新已经存在的数据') }}-->
        <!--        </div>-->
        <div slot="tip" class="el-upload__tip" style="color:red">
          {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
          <el-link type="primary" style="font-size:12px" @click="fetchTemplate">
            {{ $t('下载模板') }}
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDealFinancingRepayment, delDealFinancingRepayment } from '@/api/deal/financing/repayment/dealFinancingRepayment'
import dealFinancingRepaymentForm from './dealFinancingRepaymentForm.vue'
import { getToken } from '@/utils/auth'
export default {
    components: {
        dealFinancingRepaymentForm
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 总条数
          total: 0,
          // 还款计划表格数据
          dealFinancingRepaymentList: [],
          // 弹出层标题
          title: '还款计划',
          // 是否显示弹出层
          formOpen: false,
          // 查询参数
          queryParams: {
              dealId: this.$route.query.id,
              startDate: undefined,
              endDate: undefined,
              pageNum: 1,
              pageSize: 10
          },
          repaymentDate: [],
          // 表单参数
          form: {},
          // 表单校验
          rules: {},
          // 用户导入参数
          upload: {
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: '',
            // 是否禁用上传
            isUploading: false,
            // 是否更新已经存在的用户数据
            updateSupport: 0,
            // dealId
            dealId: this.$route.query.id,
            // 设置上传的请求头部
            headers: { Authorization: 'Bearer ' + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + '/repayment/dealFinancingRepayment/importData'
          }
      }
  },
  created() {
      this.getList()
  },
  methods: {
    /** 查询还款计划列表 */
    getList() {
        this.loading = true
        if (this.repaymentDate != null && this.repaymentDate.length > 1) {
          this.queryParams.startDate = this.repaymentDate[0]
          this.queryParams.endDate = this.repaymentDate[1]
        } else {
          this.queryParams.startDate = undefined
          this.queryParams.endDate = undefined
        }
        listDealFinancingRepayment(this.queryParams).then(response => {
            this.dealFinancingRepaymentList = response.rows
            this.total = response.total
            this.loading = false
        }).catch(() => {
            this.loading = false
        })
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            dealId: undefined,
            repaymentDate: undefined,
            principalPayable: undefined,
            interestPayable: undefined,
            serviceChargesPayable: undefined,
            totalAmountPayable: undefined,
            currentBalance: undefined,
            actualRepaymentDate: undefined,
            actualPrincipalPaid: undefined,
            actualInterestPaid: undefined,
            actualServiceChargePaid: undefined,
            totalAmountActuallyPaid: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.$nextTick(() => {
            this.$refs.dealFinancingRepaymentForm.init(null, undefined)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row, type) {
        this.formOpen = true
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.dealFinancingRepaymentForm.init(row, type)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(() => {
            return delDealFinancingRepayment(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(() => {
            this.loading = false
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        const queryParams = this.queryParams
        this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(() => {
            this.downLoadExcel('/repayment/dealFinancingRepayment/export', queryParams)
        }).then(response => {
            this.download(response.msg)
        }).catch(() => {
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = this.$t('导入')
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 下载模板
    fetchTemplate() {
      const href1 = window.location.href
      const href2 = this.$route.path
      const url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/repaymentPlanImportTemplate.xlsx'
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
